import React, { Component } from 'react';
import { getComment, addComment, getGequurl } from '../../utils/api';
import '../../style/all.css';
import './SongComment.css';

export default class SongComment extends Component {
	state = {
		// 评论数组
		commentList: [],
		// 当前评论的音乐id 作为请求参数发起请求
		currentMusicId: 0,
		// 当前评论的音乐的信息
		currentMusicInfo: null,
		editor: null
	}
	componentDidMount () {
		// 获取参数
		let { search } = this.props.location;
		let musicId = Number(search.split('=')[1]);
		// 发起请求获取评论
		this.getComments(musicId);
		// 发起请求获取音乐详细信息
		this.getMusicD(musicId);
		// 初始化editor
		const E = window.wangEditor;
		const editor = new E(".fb");
		editor.config.height = 150;
		editor.config.menus = [];
		editor.create();
		this.setState({
			editor: editor
		});
	}
	// 获取当前音乐的详细信息
	async getMusicD (musicId) {
		let musicD = await getGequurl(musicId);
		if (musicD.status === 0) {
			this.setState({
				currentMusicInfo: musicD.data[0],
			})
		} else {
			window.alert(musicD.message);
		}
	}
	// 获取评论
	async getComments (musicId) {
		let commentList = await getComment(0, musicId);
		if (commentList.status === 0) {
			this.setState({
				commentList: commentList.data,
				currentMusicId: musicId
			})
		} else {
			window.alert(commentList.message);
		}
	}
	// 发表评论
	async comment (musicId) {
		let { editor } = this.state;
		if (editor.txt.text().trim().length === 0) {
			window.alert('评论不能为空！');
			return;
		}
		let userid = Number(window.sessionStorage.getItem('userid'));
		let addC = await addComment(userid, 0, musicId, this.state.editor.txt.text(), new Date().toLocaleString());
		if (addC.status === 0) {
			editor.txt.clear();
			// 刷新评论
			this.getComments(musicId);
		} else {
			window.alert(addC.message);
		}
	}
	render () {
		let { commentList, currentMusicId, currentMusicInfo } = this.state;
		return (
			<div className="songComment">
				<div className='back red' onClick={() => { this.props.history.goBack(); }}>&lt;返回</div>
				<h2 className='musicD'>{currentMusicInfo !== null ? currentMusicInfo.music_name +' -- '+ currentMusicInfo.singer_name : ""}</h2>
				<div className='comment'>
					<div className='fb'></div>
					<div className='dianjifb' onClick={() => { this.comment(currentMusicId) }}>发表评论</div>
					<h2>评论列表({commentList.length})</h2>
					<ul>
						{commentList.map((item) => (
							<li key={item.commentid}>
								<div className='ava'>
									<img width="100%" height="100%" src={"http://localhost:3001/" + item.user_avator_url} alt="" />
								</div>
								<div className='comment_content'>
									<span>{item.user_nickname}</span>
									<p>
										{item.comment_content}
									</p>
									<span>{item.comment_create_time}</span>
								</div>
							</li>
						))}
					</ul>
				</div>
			</div>
		)
	}
}
